import json
import asyncio
import os
import sys
import websockets
from server import Server

# 设置窗口基本信息
title = "服务端文件同步程序"
motd = "[INFO] 将程序与配置文件放于同步文件夹中,保持进程运行即可..."
os.system("title " + title)
os.system("color f0")
print("[INFO] 软件作者21Hertz, 联系QQ2021583736")
print(motd)

# 从配置文件读取配置
try:
    with open("config.json", "r") as f:
        config = json.loads(f.read())
    host = "0.0.0.0"
    port = config["port"]
    workdir = config["workdir"]
    main_dict = config["settings"]
    os.chdir(workdir)
    print(f"[INFO] 当前使用端口: {port}")
    print(f"[INFO] 当前工作目录: {os.getcwd()}")
except Exception as error:
    input(f"[INFO] 启动失败! 配置有误:\n{error}")
    sys.exit()
# 实例化对象
myServer = Server(main_dict)


# ws响应函数
async def echo(websocket):
    try:
        async for message in websocket:
            try:
                request = json.loads(message)
                if request["action"] == "GetInfo":
                    info_dict = json.dumps(myServer.createDict())
                    await websocket.send(info_dict)
                elif request["action"] == "GetFile":
                    with open(request["name"], "rb") as file:
                        while True:
                            part = file.read(1024000)
                            if not part:
                                break
                            await websocket.send(part)
                    await websocket.send("complete!")
            except Exception as err:
                print(f"[INFO] 非法请求: {err}")
    except Exception as err:
        pass


# 启动websocket进程
async def main():
    # 使用 ping_interval=None 参数取消心跳防止断开连接
    async with websockets.serve(echo, host, port, ping_interval=None):
        await asyncio.Future()  # run forever


asyncio.run(main())

# pyinstaller -F main.py -i "logo.ico"
